import ajax from "../js/ajax.js";
let dataArr=[]
if(!localStorage.getItem("bookdata")){
    ajax({
        url:"https://api.iynn.cn/mock",
        data:{
          "t":2
        }
    }).then(res=>{
        console.log(res);
        if(res.code==0)
        dataArr = res.data
        localStorage.setItem('bookdata', JSON.stringify(dataArr))
        render(dataArr)
        location.href=""
    })
}else{
    dataArr = JSON.parse(localStorage.getItem('bookdata'))
    render(dataArr)
}


// 渲染函数
function render(arr){
    let str =""
    arr.forEach(function(item,index){
        str+=` <tr>
        <td>${index+1}</td>
        <td>${item.title}</td>
        <td>${item.user}</td>
        <td>${item.date}</td>
        <td id="cz"><a class="del" id="${item.id}">删除</a><a class="write" id="${item.id}">编辑</a></td>
  </tr>`
    })
    document.querySelector('tbody').innerHTML = str
    // 调用删除函数
    del()
    // 调用修改函数
    wt()
}

let book =document.querySelector(".bookname")
let user =document.querySelector(".username")
let date = document.querySelector(".date")
// 添加功能
document.querySelector(".add").onclick=function(){
     dataArr.push({
         id:Number(dataArr[dataArr.length - 1].id) + 1,
         title:book.value,
         user:user.value,
         date:date.value
     })
     book.value=""
     user.value=""
     date.value=""
     localStorage.setItem('bookdata', JSON.stringify(dataArr))
     render(dataArr)
}

// 删除功能
function del(){
let del =document.querySelectorAll(".del")
del.forEach(function(item){
    item.onclick=function(){
        dataArr.forEach(function(item1,index){
            if(item.id==item1.id){
              dataArr.splice(index,1)
              localStorage.setItem('bookdata', JSON.stringify(dataArr))
             render(dataArr)
            }
        })
    }
})
}



// 修改功能
function wt(){
   let agbookname=document.querySelector(".agbookname")
   let aguser=document.querySelector(".aguser")
   let agdate=document.querySelector(".agdate")
   let update=document.querySelector("#update")
   document.querySelectorAll(".write").forEach(function(item){
       item.onclick=function(){
        $('#myModal').modal('show')
         dataArr.forEach(function(item1){
             if(item1.id==item.id){
                //  回填数据
                agbookname.value=item1.title
                aguser.value=item1.user
                agdate.value=item1.date
              
                // 修改数据
              update.onclick=function(){
                item1.title=agbookname.value
                item1.user=aguser.value
                item1.date=agdate.value
                localStorage.setItem('bookdata', JSON.stringify(dataArr))
                render(dataArr)
              }
             }
         })
       }
   })
}